package cn.cloudmenu.android;

import java.net.URI;

import org.json.JSONObject;

import android.webkit.WebView;

import cn.cloudmenu.android.activity.Courses;

import com.strumsoft.websocket.phonegap.WebSocket;

public class CoursesWebSocket extends WebSocket {
	private MenuCoverBean menu;
	private Courses coursesActivity;

	public CoursesWebSocket(WebView appView, URI uri, UserProfile user, MenuCoverBean menu, Courses coursesActivity) {
		super(appView, uri, Draft.DRAFT76, user.getNickname());
		this.menu = menu;
		this.coursesActivity = coursesActivity;
	}

	public void onMessage(final String msg) {
		super.onMessage(msg);
		try {
			JSONObject json = new JSONObject(msg);
			String command = json.getString("command");
			System.out.println("---0000000000))))))))))))))))))))))))))))))CoursesWebSocket.onMessage()  msg = " + msg);
			if ("message".equals(command)) {
				String message = json.getString("message");
				message = java.net.URLDecoder.decode(message, "utf-8");
				coursesActivity.setMessage(message);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void onOpen() {
		super.onOpen();
		System.out.println("---0000000000))))))))))))))))))))))))))))))CoursesWebSocket onOpen() ");
		try {// 不管是“新开桌”还是“加入桌”，到了Courses Activity 都以加入方式，获取当前桌子状态即可。
			JSONObject command = new JSONObject();
			command.put("command", "join");
			command.put("menuId", menu.getId());
			command.put("menuName", menu.getName());
			String tableName = coursesActivity.getIntent().getStringExtra("tableName");
			String opener = coursesActivity.getIntent().getStringExtra("opener");
			command.put("tableName", tableName);
			command.put("opener", opener);
			System.out.println("command =" + command + " menuId=" + menu.getId() + " tableName=" + tableName
					+ " opener=" + opener);

			this.send(command.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void orderCourse(MenuCourseBean course) {
		try {// 不管是“新开桌”还是“加入桌”，到了Courses Activity 都以加入方式，获取当前桌子状态即可。
			JSONObject command = new JSONObject();
			command.put("command", "dish");
			command.put("courseId", course.getId());
			command.put("price", course.getPrice());
			System.out.println("command =" + command + " courseId=" + course.getId() + " price=" + course.getPrice());

			this.send(command.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void onClose() {
		super.onClose();
		System.out.println("---0000000000))))))))))))))))))))))))))))))CoursesWebSocket onClose() ");
	}

	public void onError(final Throwable t) {
		super.onError(t);
		System.out.println("---0000000000))))))))))))))))))))))))))))))CoursesWebSocket onError() t.getMessage() = "
				+ t.getMessage());
	}

}
